<template>
  <n-card :bordered="false" content-style="padding:0">
    <n-form
      ref="formRef"
      :model="query"
      size="small"
      label-placement="left"
      :show-feedback="false"
      inline
    >
      <n-grid cols="s:1 m:2 l:3 xl:4" :x-gap="20" :y-gap="20" responsive="screen">
        <n-form-item-gi label-placement="left" label="用户名称">
          <n-input v-model:value="query.userName" placeholder="请输入用户名称" />
        </n-form-item-gi>

        <n-form-item-gi label-placement="left" label="手机号">
          <n-input v-model:value="query.phonenumber" placeholder="请输入手机号码" />
        </n-form-item-gi>

        <n-form-item-gi>
          <n-space>
            <n-button type="primary" @click="handleSearch">查询</n-button>
            <n-button @click="handleReset">重置</n-button>
          </n-space>
        </n-form-item-gi>
      </n-grid>
    </n-form>
  </n-card>

  <n-space class="py-[10px]" justify="end">
    <n-button
      ghost
      type="error"
      size="small"
      v-hasPermi="['system:role:remove']"
      :disabled="checkedRows.length === 0"
      @click="handleCancelUsers"
    >
      <template #icon>
        <n-icon size="18"><CloseFilled /></n-icon>
      </template>
      批量取消授权
    </n-button>

    <n-button
      ghost
      type="primary"
      size="small"
      v-hasPermi="['system:role:add']"
      @click="openDialog({ roleId: route.params.roleId })"
    >
      <template #icon>
        <n-icon size="18"><PlusRound /></n-icon>
      </template>
      添加用户
    </n-button>
  </n-space>

  <n-data-table
    ref="tableRef"
    :loading="loading"
    :columns="columns"
    :data="tableData"
    :row-key="(row: any) => row.userId"
    :pagination="{
      page: query.page,
      pageSize: query.pageSize,
      itemCount: total,
      showSizePicker: true,
      onUpdatePage: handlePageChange,
      onUpdatePageSize: handlePageSizeChange,
    }"
    @update:checked-row-keys="handleChcekedRowKeys"
  />

  <!-- 选择用户弹窗 -->
  <SelectUsersDialog :visible="visible" :data="data" @close="closeDialog"></SelectUsersDialog>
</template>

<script lang="tsx" setup>
import { ref } from 'vue';
import { useRoute } from 'vue-router';
import { useTable } from '@/hooks/useTable';
import { CloseFilled, PlusRound } from '@vicons/material';
import { getAllocatedRoleUser, cancelAuthUserAll } from '@/apis/system/role';
import {
  NButton,
  NPopconfirm,
  NSpace,
  NTag,
  useDialog as useConfirmDailog,
  useMessage,
} from 'naive-ui';
import Permisstion from '@/components/permission/index.vue';
import { useDialog } from '@/hooks/useDialog';
import SelectUsersDialog from './components/SelectUsersDialog.vue';

const dialog = useConfirmDailog();
const message = useMessage();
const route = useRoute();
const checkedRows = ref<any>([]);

const columns = [
  {
    type: 'selection',
    width: 50,
    align: 'center',
  },
  {
    title: '用户名称',
    key: 'userName',
  },
  {
    title: '用户昵称',
    key: 'nickName',
  },
  {
    title: '邮箱',
    key: 'email',
  },
  {
    title: '手机',
    key: 'phonenumber',
  },
  {
    title: '状态',
    key: 'status',
    render: (row: any) => (
      <NTag size="small" type={row.status === '0' ? 'success' : 'error'}>
        {row.status === '0' ? '正常' : '停用'}
      </NTag>
    ),
  },
  {
    title: '创建时间',
    key: 'createTime',
  },
  {
    title: '操作',
    key: 'actions',
    render: (row: any) => (
      <NSpace>
        <Permisstion hasPermi={['system:role:remove']}>
          <NPopconfirm
            positiveText="确定"
            negativeText="取消"
            onPositiveClick={async () => {
              row.cancelLoading = true; // 确定按钮loading
              await cancelAuthUsers([row]);
              row.cancelLoading = false;
            }}
            positive-button-props={{
              loading: row.cancelLoading,
            }}
            v-slots={{
              trigger: () => (
                <NButton text type="primary" size="tiny">
                  取消授权
                </NButton>
              ),
            }}
          >
            确认要取消该用户 {row.userName} 的授权吗？
          </NPopconfirm>
        </Permisstion>
      </NSpace>
    ),
  },
];

// useTable 获取表格数据
const {
  query,
  tableData,
  total,
  loading,
  loadData,
  handleSearch,
  handleReset,
  handlePageChange,
  handlePageSizeChange,
  refresh,
  pagination,
} = useTable({
  api: getAllocatedRoleUser,
  defaultQuery: {
    roleId: route.params.roleId,
    userName: null,
    phonenumber: null,
  },
});

// 选择用户弹窗
const { visible, data, openDialog, closeDialog } = useDialog();

function handleChcekedRowKeys(keys: Array<string | number>, rows: object[]) {
  checkedRows.value = rows;
}

/**
 * 取消授权用户
 * @param rows
 */
async function cancelAuthUsers(rows: any) {
  try {
    const userIds = rows.map((item: any) => item.userId);
    const res: any = await cancelAuthUserAll({ roleId: route.params.roleId, userIds });
    if (res.code === 200) {
      message.success('操作成功');
      refresh();
      checkedRows.value = []; // reset选中状态
    }
  } catch (error) {}
}

async function handleCancelUsers() {
  // cancelUsersLoading.value = true;
  let loading = false;
  const userNames = checkedRows.value.map((item: any) => item.userName).join(',');
  dialog.warning({
    title: '取消授权用户',
    content: `确定要取消选中的 ${userNames} 用户的授权吗？`,
    positiveText: '确定',
    negativeText: '取消',
    positiveButtonProps: {
      loading: loading,
    },
    onPositiveClick: async () => {
      loading = true;
      await cancelAuthUsers(checkedRows.value);
      loading = false;
    },
  });
}
</script>

<style lang="less" scoped></style>
